import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/finance/models/transaction_model.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 分类饼图组件
class CategoryPieChart extends StatelessWidget {
  final String title;
  final Map<String, int> categoryStats;
  final TransactionType type;

  const CategoryPieChart({
    Key? key,
    required this.title,
    required this.categoryStats,
    required this.type,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      // 添加溢出处理
      clipBehavior: Clip.none,
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: AppTheme.surfaceColor,
        borderRadius: BorderRadius.circular(12.r),
        boxShadow: AppTheme.lightShadow,
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (categoryStats.isEmpty)
            _buildEmptyState()
          else
            _buildContent(),
        ],
      ),
    );
  }

  /// 构建内容
  Widget _buildContent() {
    // 计算总金额
    final total = categoryStats.values.fold(0, (sum, amount) => sum + amount);

    // 按金额排序并获取前3个分类
    final sortedCategories = categoryStats.entries.toList()
      ..sort((a, b) => b.value.compareTo(a.value));

    final topCategories = sortedCategories.take(3).toList();
    final hasOthers = sortedCategories.length > 3;

    // 计算其他分类的总金额
    int othersAmount = 0;
    if (hasOthers) {
      for (int i = 3; i < sortedCategories.length; i++) {
        othersAmount += sortedCategories[i].value;
      }
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: TextStyle(
            fontSize: 14.sp,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(height: 8.h),
        Row(
          children: [
            // 饼图
            SizedBox(
              width: 80.r,
              height: 80.r,
              child: CustomPaint(
                painter: PieChartPainter(
                  values: [
                    ...topCategories.map((e) => e.value / total),
                    if (hasOthers) othersAmount / total,
                  ],
                  colors: [
                    ...topCategories
                        .map((e) => _getCategoryColor(e.key, type)),
                    if (hasOthers) Colors.grey,
                  ],
                ),
              ),
            ),
            SizedBox(width: 12.w),
            // 图例
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ...topCategories.map(
                    (entry) => _buildLegendItem(
                      entry.key,
                      entry.value,
                      total,
                      _getCategoryColor(entry.key, type),
                    ),
                  ),
                  if (hasOthers)
                    _buildLegendItem(
                      '其他',
                      othersAmount,
                      total,
                      Colors.grey,
                    ),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Padding(
      padding: EdgeInsets.all(12.r),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
          SizedBox(height: 16.h),
          Center(
            child: Column(
              children: [
                Icon(
                  Icons.pie_chart_outline,
                  size: 40.r,
                  color: Colors.grey[400],
                ),
                SizedBox(height: 8.h),
                Text(
                  '暂无数据',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: Colors.grey[600],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建图例项
  Widget _buildLegendItem(String category, int amount, int total, Color color) {
    final percentage = (amount / total * 100).toStringAsFixed(1);
    final amountText = '¥${amount.toStringAsFixed(2)}';

    return Padding(
      padding: EdgeInsets.only(bottom: 4.h),
      child: Row(
        children: [
          Container(
            width: 12.r,
            height: 12.r,
            decoration: BoxDecoration(
              color: color,
              shape: BoxShape.circle,
            ),
          ),
          SizedBox(width: 4.w),
          Expanded(
            child: Text(
              category,
              style: TextStyle(
                fontSize: 12.sp,
                color: AppTheme.textPrimaryColor,
              ),
              overflow: TextOverflow.ellipsis,
            ),
          ),
          Text(
            '$percentage%',
            style: TextStyle(
              fontSize: 12.sp,
              color: AppTheme.textSecondaryColor,
            ),
          ),
        ],
      ),
    );
  }

  /// 获取分类颜色
  Color _getCategoryColor(String category, TransactionType type) {
    final baseColors = type == TransactionType.expense
        ? [
            AppTheme.expenseColor,
            AppTheme.expenseColorLight,
            AppTheme.warningColor,
            const Color(0xFFFF6B6B),
            const Color(0xFFFF8E8E),
            const Color(0xFFFFB3B3),
          ]
        : [
            AppTheme.incomeColor,
            AppTheme.incomeColorLight,
            AppTheme.successColor,
            const Color(0xFF34D399),
            const Color(0xFF6EE7B7),
            const Color(0xFF9CF3C4),
          ];

    // 根据分类名称生成一个稳定的哈希值，用于选择颜色
    final index = category.hashCode % baseColors.length;
    return baseColors[index.abs()];
  }
}

/// 饼图绘制器
class PieChartPainter extends CustomPainter {
  final List<double> values;
  final List<Color> colors;

  PieChartPainter({required this.values, required this.colors});

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2;

    // 绘制饼图
    double startAngle = -90 * (3.14159265359 / 180); // 从顶部开始（-90度）

    for (int i = 0; i < values.length; i++) {
      final sweepAngle = values[i] * 2 * 3.14159265359; // 弧度

      final paint = Paint()
        ..color = colors[i]
        ..style = PaintingStyle.fill;

      canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius),
        startAngle,
        sweepAngle,
        true,
        paint,
      );

      startAngle += sweepAngle;
    }

    // 绘制中心白色圆形，形成环形图效果
    final centerPaint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill;

    canvas.drawCircle(center, radius * 0.6, centerPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
